<template>
  <NavBar title="代理系统" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="agent-home-container">
    <!-- 余额卡片 -->
	<view class="balance-card-bgc">
     <view class="balance-card">
      <view class="balance-header">
        <text class="balance-label">余额</text>
        <view class="record-link" @click="goToRecord">
          <text class="record-text">金额记录</text>
          <view class="arrow">
             <uni-icons type="right" color="#FFFFFF" size="20" ></uni-icons>
          </view>
        </view>
      </view>
      <text class="balance-amount">¥{{ agentCash.toFixed(2) }}</text>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <view class="action-btn" @click="openRecharge">
          <text class="btn-text">充值</text>
        </view>
        <view class="action-btn" @click="exportData">
          <text class="btn-text">导出</text>
        </view>
        <view class="action-btn" @click="openCardGenerate">
          <text class="btn-text">卡密生成</text>
        </view>
      </view>
    </view>
	</view>
	<view class="centre-bgc">
    <!-- 中心区域背景图片 -->
    <image class="centre-bg-image" src="/static/bgc1.png" mode="scaleToFill"></image>

    <!-- 搜索框 -->
    <view class="search-section">
      <input
        class="search-input"
        placeholder="请输入卡密"
        v-model="searchKeyword"
        @input="onSearchInput"
        @confirm="onSearch"
      />

	  <image class="search-icon" src="/static/search.png" mode="" @click="onSearch"></image>
    </view>
    
    <!-- 标签页 -->
    <view class="tab-container">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        <text class="tab-text">全部</text>
        <view class="tab-indicator" v-if="activeTab === 'all'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'unused' }"
        @click="switchTab('unused')"
      >
        <text class="tab-text">未使用</text>
        <view class="tab-indicator" v-if="activeTab === 'unused'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'used' }"
        @click="switchTab('used')"
      >
        <text class="tab-text">已使用</text>
        <view class="tab-indicator" v-if="activeTab === 'used'"></view>
      </view>
    </view>
    
    <!-- 记录列表 -->
    <scroll-view
      class="record-list-container"
      scroll-y="true"
      @scrolltolower="onScrollToLower"
      lower-threshold="100"
    >
      <view class="record-list">
        <view
          class="record-item"
          v-for="record in filteredRecords"
          :key="record.id"
          :class="{ 'voided': record.status === 2 }"
        >
          <!-- 背景图片 -->
          <image
            class="record-bg-image"
            :src="record.status === 0 ? '/static/home1.png' : '/static/home2.png'"
            mode="scaleToFill"
          ></image>

          <!-- 已作废状态的灰色横线 -->
          <view v-if="record.status === 2" class="voided-line"></view>

          <view class="record-header">
            <view class="record-title">{{ record.batch }}
			 <view v-if="record.status === 0" class="divide"></view>
			 <image v-if="record.status === 0" class="card-icon-copy" src="/static/home5.png" mode="" @click="copyBatch(record.batch)"></image></view>
            <text class="record-date">{{ record.date }}</text>
          </view>
		  <view class="divide-right">
			  
		  </view>
          <view class="record-content">
            <view class="card-icon">
              <image class="card-icon-email" src="/static/home3.png" mode=""></image>
            </view>
            <text class="card-code">{{ record.cardCode }}</text>
  		   <view class="card-code-copy" @click="copyCardCode(record.rawData.card_key)"> <image  class="card-icon-email" src="/static/home4.png" mode=""></image></view>

            <view class="face-value">
              <text class="value-label">面值</text>
              <text class="value-amount" :class="{ 'status-active': record.status === 0, 'status-inactive': record.status !== 0 }">{{ record.faceValue }}</text>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="load-more" v-if="loading || hasMore">
          <view v-if="loading" class="loading-text">
            <text>加载中...</text>
          </view>
          <view v-else-if="hasMore" class="load-more-text">
            <text>上拉加载更多</text>
          </view>
        </view>

        <!-- 没有更多数据 
        <view class="no-more" v-if="!hasMore && cardKeyList.length > 0">
          <text class="no-more-text">没有更多数据了</text>
        </view>-->
      </view>
    </scroll-view>
    </view>
    <!-- 充值弹窗 -->
    <uni-popup ref="rechargePopup" type="bottom" :mask-click="true" :safe-area="false">
      <view class="recharge-modal">
        <view class="modal-header">
          <text class="modal-title">充值</text>
          <view class="close-btn" @click="closeRecharge">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="modal-content">
          <view class="input-section">
            <text class="input-label">充值金额</text>
            <input 
              class="amount-input" 
              placeholder="最低数量为1"
              v-model="rechargeAmount"
              type="number"
            />
            <view class="balance-info">可用余额: {{ agentCash.toFixed(2) }}元</view>
          </view>
          
          <view class="payment-section">
            <text class="payment-label">选择支付方式</text>
            <view class="payment-options">
              <view
                class="payment-item"
                v-for="method in availablePaymentMethods"
                :key="method.key"
                @click="selectPayment(method.key)"
              >
                <image
                  :class="method.key === 'wechat' ? 'payment-icon' : 'payment-icon-zfb'"
                  :src="method.icon"
                  mode=""
                ></image>
                <text class="payment-text">{{ method.name }}</text>
                <image
                  class="check-icon"
                  v-if="selectedPayment === method.key"
                  src="/static/tuoyuan1.png"
                  mode=""
                ></image>
                <image
                  v-else
                  class="check-icon-moren"
                  src="/static/tuoyuan.png"
                  mode=""
                ></image>
              </view>
            </view>
          </view>
		  <view class="pay-button" @click="confirmPayment">
		    <text class="pay-text">立即支付</text>
		  </view>
        </view>
     
      </view>
    </uni-popup>
    
    <!-- 卡密生成弹窗 -->
    <uni-popup ref="cardGeneratePopup" type="bottom" :mask-click="false">
      <view class="card-generate-modal">
        <view class="modal-header">
          <text class="modal-title">卡密生成</text>
          <view class="close-btn" @click="closeCardGenerate">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="modal-content">
          <view class="card-type-section">
            <text class="section-label">选择要生成的卡密类型</text>
            <view class="card-type-options">
              <view 
                class="card-type-item" 
                :class="{ active: cardType === 'times' }"
                @click="selectCardType('times')"
              >
          <image class="check-icon"   v-if="cardType === 'times'" src="/static/tuoyuan1.png" mode=""></image>
				  <image v-else class="check-icon-moren" src="/static/tuoyuan.png" mode=""></image>
				<text class="card-type-text">次卡</text>
              </view>
              <view 
                class="card-type-item" 
                :class="{ active: cardType === 'svip' }"
                @click="selectCardType('svip')"
              >
          <image class="check-icon"   v-if="cardType === 'svip'" src="/static/tuoyuan1.png" mode=""></image>
				  <image v-else class="check-icon-moren" src="/static/tuoyuan.png" mode=""></image>
				<text class="card-type-text">SVIP卡</text>
              </view>
            </view>
          </view>
          
          <view class="input-section">
            <text class="input-label">生成数量</text>
            <input
              class="form-input"
              placeholder="最低数量为1"
              v-model="generateQuantity"
              type="number"
            />
          </view>

          <view class="input-section" v-if="cardType === 'times'">
            <text class="input-label">卡密面值</text>
            <input
              class="form-input"
              placeholder="最低面值为20"
              v-model="faceValue"
              type="number"
            />
          </view>
		  <view class="payment-section kami">
		    <text class="payment-info">需支付: {{ calculateCost().toFixed(2) }}元</text>
		    <view class="pay-button-zhifu" @click="confirmGenerate">
		      <text class="pay-text">余额支付</text>
		    </view>
		  </view>
        </view>
      
      </view>
    </uni-popup>
  </view>
  </NavBar>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { AGENT_API } from '../../config/api.js'
import { getCurrentUser, getToken, fetchUserInfo } from '../../utils/user.js'
import { getAgentConfig } from '../../utils/config.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'

// 响应式数据
const activeTab = ref('all')
const searchKeyword = ref('')
const rechargeAmount = ref('')
const selectedPayment = ref(isWeixinMiniProgram() ? 'wechat' : 'alipay')
const cardType = ref('times')
const generateQuantity = ref('')
const faceValue = ref('')

// 用户数据
const userInfo = ref(null)
const agentCash = ref(0)

// 代理商配置数据
const agentConfig = ref({
  svip_price: 0,
  package_price: 0
})

// 判断当前平台
const isWeixinMP = ref(isWeixinMiniProgram())

// 计算可用的支付方式
const availablePaymentMethods = computed(() => {
  const methods = []

  if (isWeixinMP.value) {
    // 微信小程序：只显示微信支付
    methods.push({ key: 'wechat', name: '微信', icon: '/static/svip10.png' })
  } else {
    // 非微信小程序：只显示支付宝支付
    methods.push({ key: 'alipay', name: '支付宝', icon: '/static/svip8.png' })
  }

  return methods
})

// 卡密列表数据
const cardKeyList = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const hasMore = ref(true)
const total = ref(0) // 总数据量

// 弹窗引用
const rechargePopup = ref()
const cardGeneratePopup = ref()

// 格式化卡密显示（四段显示，每段四个字符，用-分割）
const formatCardKey = (cardKey) => {
  if (!cardKey) {
    return ''
  }

  // 将卡密分成四段，每段四个字符
  const segments = []
  for (let i = 0; i < cardKey.length; i += 4) {
    segments.push(cardKey.slice(i, i + 4))
  }

  return segments.join('-')
}

// 获取状态显示文本
const getStatusText = (status, batchId) => {
  switch (status) {
    case 0:
      return `批次 ${batchId}`
    case 1:
      return '已使用'
    case 2:
      return '已作废'
    default:
      return `批次 ${batchId}`
  }
}

// 获取状态显示时间
const getStatusTime = (status, createdAt, updatedAt) => {
  switch (status) {
    case 0:
      return '' // 未使用不显示时间
    case 1:
      return updatedAt || createdAt // 已使用显示使用时间
    case 2:
      return updatedAt || createdAt // 已作废显示作废时间
    default:
      return ''
  }
}

// 获取面值显示
const getFaceValue = (cardType, cardValue) => {
  if (cardType === 1) {
    return 'SVIP'
  } else {
    return cardValue ? cardValue.toString() : '0'
  }
}

// 处理API数据为显示格式
const processCardKeyData = (apiData) => {
  if (!apiData || !apiData.list) {
    return []
  }

  return apiData.list.map(item => ({
    id: item.id,
    batch: getStatusText(item.status, item.batch_id),
    date: getStatusTime(item.status, item.created_at, item.updated_at),
    cardCode: formatCardKey(item.card_key),
    faceValue: getFaceValue(item.card_type, item.card_value),
    status: item.status,
    cardType: item.card_type,
    rawData: item // 保存原始数据以备后用
  }))
}

// 计算属性 - 根据当前标签过滤记录
const filteredRecords = computed(() => {
  // cardKeyList.value现在是一个数组，需要包装成对象传递给processCardKeyData
  let filtered = processCardKeyData({ list: cardKeyList.value || [] })

  if (activeTab.value === 'unused') {
    filtered = filtered.filter(record => record.status === 0)
  } else if (activeTab.value === 'used') {
    filtered = filtered.filter(record => record.status === 1)
  }

  if (searchKeyword.value) {
    filtered = filtered.filter(record =>
      record.cardCode.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  return filtered
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const goToRecord = () => {
  uni.navigateTo({
    url: '/pages/amount-record/amount-record'
  })
}

const switchTab = (tab) => {
  activeTab.value = tab
  // 切换标签页时重新加载数据
  fetchCardKeyList(true)
}

// 验证卡密格式
const validateCardKeyFormat = (cardKey) => {
  if (!cardKey || !cardKey.trim()) {
    return { valid: true, message: '' } // 空值允许，表示清空搜索
  }

  const trimmedKey = cardKey.trim()

  // 检查格式：XXXX-XXXX-XXXX-XXXX
  const cardKeyPattern = /^[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}$/

  if (!cardKeyPattern.test(trimmedKey)) {
    return {
      valid: false,
      message: '卡密格式不正确，请输入格式：XXXX-XXXX-XXXX-XXXX'
    }
  }

  return { valid: true, message: '' }
}

// 将格式化的卡密转换为API需要的格式（去除"-"）
const formatCardKeyForAPI = (cardKey) => {
  if (!cardKey || !cardKey.trim()) {
    return ''
  }
  return cardKey.trim().replace(/-/g, '')
}

// 监听搜索输入变化
const onSearchInput = () => {
  // 如果用户清空了搜索框，重新加载第一页卡密数据
  if (!searchKeyword.value || !searchKeyword.value.trim()) {
    fetchCardKeyList(true)
  }
}

// 执行搜索
const onSearch = () => {
  // 如果搜索框为空，提示用户输入卡密
  if (!searchKeyword.value || !searchKeyword.value.trim()) {
    uni.showToast({
      title: '卡密不能为空',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 验证卡密格式
  const validation = validateCardKeyFormat(searchKeyword.value)

  if (!validation.valid) {
    uni.showToast({
      title: validation.message,
      icon: 'none',
      duration: 3000
    })
    return
  }

  // 格式正确，执行搜索
  fetchCardKeyList(true)
}

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log('滚动到底部，检查是否需要加载更多数据')

  // 如果正在加载或没有更多数据，则不执行
  if (loading.value || !hasMore.value) {
    console.log('跳过加载：', { loading: loading.value, hasMore: hasMore.value })
    return
  }

  // 如果有搜索关键词，不自动加载更多（搜索结果通常不需要分页）
  if (searchKeyword.value && searchKeyword.value.trim()) {
    console.log('搜索模式下不自动加载更多')
    return
  }

  console.log('开始加载下一页数据，当前页：', currentPage.value)

  // 增加页码并加载下一页
  currentPage.value++
  fetchCardKeyList(false)
}

const openRecharge = () => {
  rechargePopup.value.open()
}

const closeRecharge = () => {
  rechargePopup.value.close()
}

const selectPayment = (payment) => {
  selectedPayment.value = payment
}

const confirmPayment = async () => {
  if (!rechargeAmount.value) {
    uni.showToast({
      title: '请输入充值金额',
      icon: 'none'
    })
    return
  }

  if (parseFloat(rechargeAmount.value) < 1) {
    uni.showToast({
      title: '最低充值金额为1元',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '提交中...'
    })

    const token = getToken()
    const payMethod = selectedPayment.value === 'wechat' ? 1 : 2

    const requestData = {
      amount: parseFloat(rechargeAmount.value),
      pay_method: payMethod
    }

    const response = await uni.request({
      url: AGENT_API.RECHARGE,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: requestData
    })

    uni.hideLoading()

    if (response.statusCode === 200 && response.data.code === 200) {
      // 根据支付方式处理不同的响应
      if (selectedPayment.value === 'wechat') {
        // 微信支付需要调起支付
        const paymentData = response.data.data
        await callWechatPay(paymentData.pay_data)
      } else if (selectedPayment.value === 'alipay') {
        // 支付宝支付需要调起支付
        const paymentParams = response.data.data
        await callAlipay(paymentParams)
      }
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '充值失败，请重试'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }

  } catch (error) {
    uni.hideLoading()
    console.error('充值失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  }
}

// 调起微信支付
const callWechatPay = async (payData) => {
  try {
    console.log('微信支付参数:', payData)

    // #ifdef MP-WEIXIN
    await wx.requestPayment({
      timeStamp: payData.timestamp,
      nonceStr: payData.noncestr,
      package: payData.package,
      signType: 'RSA',
      paySign: payData.sign
    })

    console.log('微信支付成功')

    // 刷新用户信息
    try {
      await fetchUserInfo()
      console.log('用户信息刷新成功')
    } catch (error) {
      console.error('刷新用户信息失败:', error)
    }

    // 调用刷新用户信息之后刷新页面上的代理商余额
    const user = getCurrentUser()
    if (user && user.agent_cash !== undefined) {
      agentCash.value = user.agent_cash
    }

    uni.showToast({
      title: '支付成功',
      icon: 'success'
    })

    // 根据需求，支付成功后不跳转界面
    console.log('微信支付成功，不跳转界面')

    // 关闭充值弹窗
    closeRecharge()
    // #endif

    // #ifndef MP-WEIXIN
    uni.showToast({
      title: '当前环境不支持微信支付',
      icon: 'error'
    })
    // #endif
  } catch (error) {
    if (error.errMsg === 'requestPayment:fail cancel') {
      uni.showToast({
        title: '支付已取消',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: '支付失败',
        icon: 'error'
      })
    }
  }
}

// 调起支付宝支付
const callAlipay = async (paymentParams) => {
  try {
    console.log('支付宝支付参数:', paymentParams)

    // 检查是否有支付宝支付数据
    if (!paymentParams || !paymentParams.pay_data || !paymentParams.pay_data.order_string) {
      throw new Error('支付参数不完整')
    }

    // 使用uni.requestPayment调起支付宝支付
    await uni.requestPayment({
      provider: 'alipay',
      orderInfo: paymentParams.pay_data.order_string,
      success: (res) => {
        console.log('支付宝支付成功:', res)
      },
      fail: (err) => {
        console.error('支付宝支付失败:', err)
        throw err
      }
    })

    console.log('支付宝支付成功')

    // 刷新用户信息
    try {
      await fetchUserInfo()
      console.log('用户信息刷新成功')
    } catch (error) {
      console.error('刷新用户信息失败:', error)
    }

    // 调用刷新用户信息之后刷新页面上的代理商余额
    const user = getCurrentUser()
    if (user && user.agent_cash !== undefined) {
      agentCash.value = user.agent_cash
    }

    uni.showToast({
      title: '支付成功',
      icon: 'success'
    })

    // 根据需求，支付成功后不跳转界面
    console.log('支付宝支付成功，不跳转界面')

    // 关闭充值弹窗
    closeRecharge()

  } catch (error) {
    console.error('支付宝支付错误:', error)

    // 处理不同的错误情况
    if (error.errMsg) {
      if (error.errMsg.includes('cancel')) {
        uni.showToast({
          title: '支付已取消',
          icon: 'none'
        })
      } else if (error.errMsg.includes('fail')) {
        uni.showToast({
          title: '支付失败',
          icon: 'error'
        })
      } else {
        uni.showToast({
          title: error.errMsg || '支付失败',
          icon: 'error'
        })
      }
    } else {
      uni.showToast({
        title: error.message || '支付失败',
        icon: 'error'
      })
    }
  }
}

const openCardGenerate = () => {
  cardGeneratePopup.value.open()
}

const closeCardGenerate = () => {
  cardGeneratePopup.value.close()
}

const selectCardType = (type) => {
  cardType.value = type
}

// 计算卡密生成消耗余额
const calculateCost = () => {
  const quantity = parseInt(generateQuantity.value) || 0
  const faceVal = parseInt(faceValue.value) || 0

  if (cardType.value === 'svip') {
    // SVIP卡价格 = svip_price * 数量，svip_price需要从分换算成元
    const svipPriceInYuan = agentConfig.value.svip_price / 100
    return svipPriceInYuan * quantity
  } else {
    // 次卡价格 = package_price * 面值 * 数量
    return agentConfig.value.package_price * faceVal * quantity
  }
}

const confirmGenerate = async () => {
  // 验证输入
  if (!generateQuantity.value) {
    uni.showToast({
      title: '请输入生成数量',
      icon: 'none'
    })
    return
  }

  if (cardType.value === 'times' && !faceValue.value) {
    uni.showToast({
      title: '请输入卡密面值',
      icon: 'none'
    })
    return
  }

  // 验证次卡面值最低为20
  if (cardType.value === 'times' && parseInt(faceValue.value) < 20) {
    uni.showToast({
      title: '卡密面值最低为20',
      icon: 'none'
    })
    return
  }

  // 计算消耗金额
  const cost = calculateCost()

  // 判断余额是否充足
  if (agentCash.value < cost) {
    uni.showToast({
      title: '余额不足',
      icon: 'none',
      duration: 3000
    })
    return
  }

  try {
    uni.showLoading({
      title: '生成中...'
    })

    const token = getToken()
    const requestData = {
      card_type: cardType.value === 'svip' ? 1 : 0,
      count: parseInt(generateQuantity.value)
    }

    // 次卡需要传面值参数
    if (cardType.value === 'times') {
      requestData.card_value = parseInt(faceValue.value)
    }

    const response = await uni.request({
      url: AGENT_API.CARDKEY_GENERATE,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: requestData
    })

    uni.hideLoading()

    if (response.statusCode === 200 && response.data.code === 200) {
      uni.showToast({
        title: '生成成功',
        icon: 'success'
      })

      // 刷新用户信息
      try {
        await fetchUserInfo()
        console.log('用户信息刷新成功')
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }

      // 更新页面余额显示
      const user = getCurrentUser()
      if (user && user.agent_cash !== undefined) {
        agentCash.value = user.agent_cash
      }

      // 重新加载卡密列表，从第一页开始
      try {
        await fetchCardKeyList(true)
        console.log('卡密列表刷新成功')
      } catch (error) {
        console.error('刷新卡密列表失败:', error)
      }

      closeCardGenerate()
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '生成失败，请重试'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }

  } catch (error) {
    uni.hideLoading()
    console.error('生成卡密失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  }
}

const copyCardCode = (code) => {
  uni.setClipboardData({
    data: code,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      })
    }
  })
}

const copyBatch = (batch) => {
  uni.setClipboardData({
    data: batch,
    success: () => {
      uni.showToast({
        title: '批次复制成功',
        icon: 'success'
      })
    }
  })
}

const exportData = () => {
  uni.showToast({
    title: '请联系客服导出',
    icon: 'none',
    duration: 3000
  })
}

// 初始化用户数据
const initUserData = () => {
  const user = getCurrentUser()
  if (user) {
    userInfo.value = user
    agentCash.value = user.agent_cash || 0
  }
}

// 初始化代理商配置
const initAgentConfig = async () => {
  try {
    const config = await getAgentConfig(true)
    agentConfig.value = {
      svip_price: config.svip_price || 5900,
      package_price: config.package_price || 5
    }
    console.log('代理商配置加载成功:', agentConfig.value)
  } catch (error) {
    console.error('加载代理商配置失败:', error)
  }
}

// 获取卡密列表
const fetchCardKeyList = async (reset = false) => {
  if (loading.value) return

  try {
    loading.value = true

    if (reset) {
      currentPage.value = 1
      cardKeyList.value = []
      hasMore.value = true
    }

    const token = getToken()
    if (!token) {
      console.error('未找到用户token')
      return
    }

    // 构建请求参数
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 如果有搜索关键词，添加搜索参数
    if (searchKeyword.value && searchKeyword.value.trim()) {
      // 将格式化的卡密转换为API需要的格式（去除"-"）
      params.card_key = formatCardKeyForAPI(searchKeyword.value)
    } else {
      // 默认按状态筛选（0=未使用）
      params.status = activeTab.value === 'all' ? undefined :
                     activeTab.value === 'unused' ? 0 :
                     activeTab.value === 'used' ? 1 : 2
    }

    // 构建查询字符串
    const queryString = Object.keys(params)
      .filter(key => params[key] !== undefined)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    const response = await uni.request({
      url: `${AGENT_API.CARDKEY_LIST}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('卡密列表API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const responseData = response.data.data || {}
      const newData = responseData.list || []

      // 更新总数据量
      total.value = responseData.total || 0

      if (reset) {
        cardKeyList.value = newData
        currentPage.value = 1
      } else {
        cardKeyList.value = [...cardKeyList.value, ...newData]
      }

      // 根据total字段判断是否还有更多数据
      const currentDataCount = cardKeyList.value.length
      hasMore.value = currentDataCount < total.value

      console.log('卡密列表加载成功:', {
        currentPage: currentPage.value,
        currentDataCount,
        total: total.value,
        hasMore: hasMore.value,
        newDataLength: newData.length
      })
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '获取卡密列表失败'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }

  } catch (error) {
    console.error('获取卡密列表失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  } finally {
    loading.value = false
  }
}

// 页面加载时初始化数据
onMounted(() => {
  initUserData()
  initAgentConfig()
  fetchCardKeyList(true)
})
</script>

<style scoped>
.agent-home-container {
  min-height: 100vh;
  position: relative;
  padding-top: 160rpx;

}
.balance-card-bgc{
	background-color: #1479FF;
	height: 410rpx;
	position: absolute;
  left: 0;
  top: 0;
  width: 100%;

}
/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 0;
  height: 88rpx;
}
.card-code-copy{
	width: 28rpx;
	height: 28rpx;
}
.time {
  font-size: 32rpx;
  font-weight: 600;
  color: #000000;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}
.card-icon-email{
	width: 33rpx;
	height: 32rpx;
}
.signal-icon,
.wifi-icon,
.battery-icon {
  width: 24rpx;
  height: 16rpx;
  background: #000000;
  border-radius: 2rpx;
}

.battery-icon {
  width: 32rpx;
  height: 16rpx;
  position: relative;
}

.battery-icon::after {
  content: '';
  position: absolute;
  right: -6rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 4rpx;
  height: 8rpx;
  background: #000000;
  border-radius: 0 2rpx 2rpx 0;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 40rpx;
  height: 88rpx;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 记录项背景图片 */
.record-bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 120rpx;
  z-index: 1;
}
.back-icon {
  font-size: 48rpx;
  font-weight: 300;
  color: #000000;
  line-height: 1;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #000000;
  flex: 1;
  text-align: center;
  margin-left: -60rpx;
}

.nav-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-btn {
  width: 40rpx;
  height: 30rpx;
  background: #F5F5F5;
  border-radius: 15rpx;
}
.kami{
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0;
}
/* 余额卡片 */
.balance-card {
	position: absolute;
	top: 100px;
	left: 50%;
	z-index: 2;
	transform: translate(-50%);
 background: linear-gradient(180deg, #5DA0FA 0%, #9DCBFF 100%);
  border-radius: 20rpx;
  padding: 40rpx;
  width: 85%;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}
.card-icon-copy{
	width: 22rpx;
	height: 22rpx;
	margin-left: 5rpx;
}
.modal-content{
	padding: 30rpx 30rpx 80rpx;
	box-sizing: border-box;
}
.balance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.balance-label {
  font-size: 36rpx;
  font-weight: 500;
  color: #fff;
}

.record-link {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.record-text {
  font-size: 32rpx;
  color: #FFFFFF;
}
.centre-bgc{
	width: 100%;
	min-height: 90vh;
	position: absolute;
	top: 380rpx;
	left: 0;
}
.divide-right{
	position: absolute;
	right: 129rpx;
	top: 0;
	height: 120rpx;
	width: 4rpx;
	border-left: 4rpx dashed #F3F5FE ;
	z-index: 9999;
}
/* 中心区域背景图片 */
.centre-bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
.arrow {
  font-size: 32rpx;
  color: #FFFFFF;
}

.balance-amount {
  display: block;
  font-size: 52rpx;
  font-weight: 700;
  color: #fff;
  margin-bottom: 40rpx;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}
.record-title{
	font-size: 22rpx;
	color: #FFFFFF;
	display: flex;
	align-items: center;
	margin-right: 5rpx;
}
.action-btn {
  flex: 1;
  height: 68rpx;
  background: #2196F3;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.divide{
	width: 2rpx;
	height: 26rpx;
	margin: 0 12rpx;
	background-color: #FFFFFF;
}
.btn-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #FFFFFF;
}

/* 搜索框 */
.search-section {
  position: relative;
  margin: 180rpx 40rpx 30rpx;
  z-index: 2;
   box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.search-input {
  width: 100%;
  height: 80rpx;
  background: #FFFFFF;
  border-radius: 12rpx;
  padding: 0 60rpx 0 30rpx;
  font-size: 28rpx;
  color: #B2B2B2;
  box-sizing: border-box;
}

.search-input::placeholder {
  color: #CCCCCC;
}

.search-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32rpx;
  color: #999999;
  width: 34rpx;
  height: 37rpx;
  cursor: pointer;
  z-index: 3;
  transition: opacity 0.3s ease;
}

.search-icon:active {
  opacity: 0.7;
}

/* 标签页 */
.tab-container {
  display: flex;
  padding: 0 40rpx;
  margin-bottom: 30rpx;
  position: relative;
  z-index: 2;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
}

.tab-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #999999;
  transition: color 0.3s ease;
}



.tab-indicator {
  width: 40rpx;
  height: 6rpx;
  background: #565FFD;
  border-radius: 3rpx;
  margin-top: 8rpx;
}

/* 记录列表容器 */
.record-list-container {
  height: calc(100vh - 500rpx); /* 根据实际布局调整高度 */
  position: relative;
  z-index: 2;
  padding-bottom: 80rpx;
}

/* 记录列表 */
.record-list {
  padding: 0 40rpx;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
}

.record-item {
  border-radius: 16rpx;
  padding: 0 10rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  height: 120rpx;
  overflow: hidden;
}

/* 已作废状态的灰色横线 */
.voided-line {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  height: 4rpx;
  background-color: #999999;
  z-index: 3;
}

.record-header {
  width: 76%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6rpx 10rpx;
  margin-bottom: 20rpx;
  position: relative;
  z-index: 2;
}

.record-batch {
  font-size: 22rpx;
  font-weight: 500;
  color: #fff;
}

.record-date {
  font-size: 24rpx;
  color: #fff;
}

.record-content {
  display: flex;
  position: relative;
  z-index: 2;
}

.card-icon {
  width: 60rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.card-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 24rpx;
  height: 24rpx;
  background: #FF6B6B;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16rpx;
  color: #FFFFFF;
  font-weight: bold;
}

.card-code {
  flex: 0.7;
  font-size: 28rpx;
  color: #999;
}

.copy-btn {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.copy-icon {
  font-size: 24rpx;
  color: #666666;
}

.face-value {
	position: absolute;
	right: 30rpx;
	top: -56rpx;
  text-align: right;
  text-align: center;
  
}

.value-label {
  display: block;
  font-size: 24rpx;
  color: #fff;
  margin-bottom: 24rpx;
}

.value-amount {
  font-size: 28rpx;
  font-weight: 600;
  margin-top: 30rpx;
}

/* 状态为0时显示蓝色 */
.value-amount.status-active {
  color: #3C8AF0;
}

/* 状态不为0时显示灰色 */
.value-amount.status-inactive {
  color: #999999;
}

/* 弹窗样式 */
.recharge-modal {
  background: #FFFFFF;
  border-radius: 36rpx 36rpx 0 0;
  max-height: 80vh;
  position: absolute;
  left: 0;
  bottom: 0rpx;
  width: 100%;
}

.card-generate-modal {
  background: #FFFFFF;
  border-radius: 36rpx 36rpx 0 0;
  max-height: 80vh;
  position: absolute;
  left: 0;
  bottom: -68rpx;
  width: 100%;
}
.modal-header {
 position: relative;
  margin-bottom: 20rpx;
  height: 114rpx;
  color: #fff;
  background-color: #565FFD;
  border-radius: 36rpx 36rpx 0 0;
}

/* 覆盖uni-popup的默认样式 */
:deep(.uni-popup__wrapper) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup__wrapper.bottom) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}
.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #fff;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-icon {
  font-size: 50rpx;
  color: #fff;
  position: absolute;
  top: 40%;
  right: 30rpx;
  transform: translateY(-50%);
}

.input-section {
  margin-bottom: 40rpx;
}

.input-label {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 24rpx;
}

.amount-input,
.form-input {
  width: 100%;
  height: 80rpx;
  background: #F5F5F5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 32rpx;
  color: #333333;
  box-sizing: border-box;
  margin-bottom: 16rpx;
}

.amount-input::placeholder,
.form-input::placeholder {
  color: #BFBFBF;
}

.balance-info {
  font-size: 28rpx;
  color: #999;
  text-align: right;
  margin-top: 20rpx;
}

.payment-section {
  margin-bottom: 40rpx;
}

.payment-label {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #999999;
  margin-bottom: 20rpx;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.payment-item {
  display: flex;
  align-items: center;
  background: #F5F5F5;
  border-radius: 12rpx;
  height: 106rpx;
  background: #FFFFFF;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
  border: 2rpx solid #E5E5E5;
  padding: 0 24rpx;
  box-sizing: border-box;
}

.payment-icon {
  width: 48rpx;
  height: 40rpx;
margin-right: 12rpx;
}

.payment-icon.wechat {
  background: #07C160;
  color: #FFFFFF;
}

.payment-icon.alipay {
  background: #1677FF;
  color: #FFFFFF;
}

.payment-text {
  flex: 1;
  font-size: 28rpx;
  color: #000;
}
.payment-icon-zfb{
	width: 48rpx;
	height: 48rpx;
	margin-right: 12rpx;
}

.radio-btn {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #E0E0E0;
  border-radius: 50%;
  position: relative;
}

.radio-btn.active {
  border-color: #2196F3;
}

.radio-btn.active::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20rpx;
  height: 20rpx;
  background: #2196F3;
  border-radius: 50%;
}

.card-type-section {
  margin-bottom: 40rpx;
}

.section-label {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 20rpx;
}

.card-type-options {
  display: flex;
  gap: 20rpx;
}

.card-type-item {
  flex: 1;
  height: 80rpx;
  border: 2rpx solid #E0E0E0;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.card-type-item.active {
  border-color: #8B5CF6;
}

.card-type-text {
  font-size: 28rpx;
  color: #333333;
}

.check-icon {
 
  width: 32rpx;
  height: 32rpx;
  
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16rpx;
  color: #FFFFFF;
  font-weight: bold;
  margin-right: 5rpx;
}
.check-icon-moren{
 width: 32rpx;
  height: 32rpx;
	  margin-right: 5rpx;
}

.payment-section {
  padding-top: 20rpx;
}

.payment-info {
  font-size: 32rpx;
  color: #666666;
  width: 50%;
  height: 92rpx;
  background-color: #F5F5F5;
  border-radius: 20rpx 0 0 20rpx;
  line-height: 92rpx;
  color: #BFBFBF;
  text-align: center;
}

.pay-button {
  background: #565FFD;
  border-radius: 20rpx;
  height: 80rpx;
  padding: 0 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pay-button-zhifu{
	width: 50%;
	background-color: #565FFD;
	height: 92rpx;
	line-height: 92rpx;
	color: #fff;
	text-align: center;
	border-radius: 0 20rpx 20rpx 0;
}
.pay-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #FFFFFF;
}

/* 加载更多样式 */
.load-more {
  padding: 30rpx 0;
  text-align: center;
}

.loading-text {
  color: #999999;
  font-size: 28rpx;
}

.load-more-text {
  color: #CCCCCC;
  font-size: 28rpx;
}

.no-more {
  padding: 30rpx 0;
  text-align: center;
}

.no-more-text {
  color: #CCCCCC;
  font-size: 28rpx;
}
</style>

